from fusionmatrix.base.model import ChatModel
from pydantic import BaseModel, Field
from loguru import logger
from os import environ, path, makedirs


class Config(BaseModel):
    chat_model: ChatModel

    @classmethod
    def get_config_path(cls) -> str:
        if 'APPDATA' in environ:
            config_path = path.join(environ['APPDATA'], 'fusionmatrix')
        elif 'HOME' in environ:
            config_path = path.join(environ['HOME'], '.fusionmatrix')
        else:
            raise Exception(f"无法确定配置文件路径")

        if not path.exists(config_path):
            makedirs(config_path, exist_ok=True)

        return config_path

    @classmethod
    def load_default_config(cls) -> 'Config':
        config_path = path.join(cls.get_config_path(), 'config.json')
        if path.exists(config_path):
            try:
                with open(config_path, 'r', encoding='utf8') as f:
                    config = Config.model_validate_json(f.read())
                    return config
            except Exception as ex:
                logger.warning(f"failed to read config from {config_path}: {ex}")

        model = ChatModel(
            api_base="https://api.siliconflow.cn/v1",
            api_key="",
            api_model_name='Qwen/Qwen2.5-7B-Instruct'
        )
        config = Config(chat_model=model)
        return config

    def save_default_config(self) -> None:
        config_path = path.join(self.get_config_path(), 'config.json')
        with open(config_path, 'w+', encoding='utf8') as f:
            f.write(self.model_dump_json())
